﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using iTextSharp.text.pdf.parser;

namespace WinFormStudy
{
    public class JpgKit
    {
        public enum ImgZipType
        {
          /// <summary>
          /// 指定高宽缩放（可能变形）
          /// </summary>
          WH = 0,
          /// <summary>
          /// 指定宽，高按比例
          /// </summary>
          W = 1,
          /// <summary>
          /// 指定高，宽按比例
          /// </summary>
          H = 2,
          /// <summary>
          /// 指定高宽裁减（不变形）
          /// </summary>
          Cut = 3,
          
          /// <summary>
          /// 按百分比压缩
          /// </summary>
          Percent=4
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="source">JPG文件路径</param>
        /// <param name="target">目标路径</param>
        /// <param name="height">高度</param>
        /// <param name="width">宽度</param>
        /// <param name="quality">压缩质量1-100</param>
        /// <param name="type"></param>
        public static bool JpgZip(string source, string target,int width, int height,float percent, int quality, ImgZipType type)
        {
            bool result=false;
            Image iSource = Image.FromFile(source);
            ImageFormat tFormat = iSource.RawFormat;

            //缩放后的宽度和高度

            int towidth = width;
            int toheight = height;
            //
            int x = 0;
            int y = 0;
            int ow = iSource.Width;
            int oh = iSource.Height;
            switch (type)
            {
                case ImgZipType.WH://指定高宽缩放（可能变形）           
                    break;
                case ImgZipType.W://指定宽，高按比例     
                    toheight = iSource.Height * width / iSource.Width;
                    break;
                case ImgZipType.H://指定高，宽按比例
                    towidth = iSource.Width * height / iSource.Height;
                    break;
                case ImgZipType.Cut://指定高宽裁减（不变形）     
                    if ((double)iSource.Width / (double)iSource.Height > (double)towidth / (double)toheight)
                    {
                        oh = iSource.Height;
                        ow = iSource.Height * towidth / toheight;
                        y = 0;
                        x = (iSource.Width - ow) / 2;
                    }
                    else
                    {
                        ow = iSource.Width;
                        oh = iSource.Width * height / towidth;
                        x = 0;
                        y = (iSource.Height - oh) / 2;
                    }
                    break;
                case ImgZipType.Percent:
                    toheight = Convert.ToInt32( iSource.Height * percent);
                    towidth = Convert.ToInt32(iSource.Width * percent);
                    break;
                default:
                break;
            }

            Bitmap ob = new Bitmap(towidth, toheight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(System.Drawing.Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource
                        , new Rectangle(x, y, towidth, toheight)
                        , new Rectangle(0,0, iSource.Width, iSource.Height)
                        , GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();     
            long[] qy = new long[1];
            qy[0] = quality;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[i];
                        break;
                    }
                }
                string extention= System.IO.Path.GetExtension(source);
                string randomFileName = System.IO.Path.GetRandomFileName();
                string filePath = System.IO.Path.Combine(target, randomFileName + extention);
                if (jpegICIinfo != null)
                {
                    ob.Save(filePath, jpegICIinfo, ep);
                }
                else
                {
                    ob.Save(filePath, tFormat);
                }
                result = true;
            }
            catch
            {
                
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
            return result;
        }
        
    }
}
